<?php
declare (strict_types=1);

namespace app\controller;


use app\model\GoodsOrders;
use app\model\GoodsShopcarOrders;
use app\Request;
use app\traits\Response;
use Yansongda\Pay\Pay;

class NotifyController
{
	use Response;
	function returnNotify(Request $request)
	{
		$paytype = $request->param('paytype');
		$config = config('pay');
		switch ($paytype) {
			case 'wechat':
				$pay = Pay::wechat($config);
				try {
					$res = $pay->callback();
				} catch (\Exception $e) {
					$this->writeJson(0, $e->getMessage());
				}
				$res = $res->resource;
				$res = $res['ciphertext'];
				$out_trade_no = $res['out_trade_no'];
				$attach = $res['attach'];
				break;
			case 'alipay':
				$pay = Pay::alipay($config);
				try {
					$res = $pay->callback();
				} catch (\Exception $e) {
					$this->writeJson(0, $e->getMessage());
				}
				$out_trade_no = $res->out_trade_no;
				$attach = $res->passback_params;
				break;
			case 'balance':
				$out_trade_no = $request->param('out_trade_no');
				$attach = $request->param('attach');
				break;
			default:
				$this->writeJson(0, '支付类型错误');
		}
		
		switch ($attach) {
			case 'goods':
				$orders = GoodsOrders::where(['order_no' => $out_trade_no, 'status' => 0])->find();
				if (!$orders) {
					$this->writeJson(0, '订单不存在');
				}
				$orders->status = 1;
				$orders->goods->sales += 1;
				$orders->paytime = time();
				$orders->together(['goods'])->save();
				break;
			case 'shopcar':
				$orders = GoodsShopcarOrders::where(['order_no' => $out_trade_no, 'status' => 0])->find();
				if (!$orders) {
					$this->writeJson(0, '订单不存在');
				}
				$orders->status = 1;
				$orders->save();
				$rows = GoodsOrders::whereIn('id', $orders->order_ids)->select();
				foreach ($rows as $row) {
					$row->status = 1;
					$row->goods->sales += 1;
					$row->paytime = time();
					$row->together(['goods'])->save();
				}
				break;
			default:
				$this->writeJson(0, '回调错误');
		}
		
		switch ($paytype) {
			case 'wechat':
			case 'alipay':
				return $pay->success();
			case 'balance':
				return true;
			default:
				$this->writeJson(0, '支付类型错误');
		}
		
	}
	
}
